<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Event;


use Psr\EventDispatcher\StoppableEventInterface;
use Selibra\Di\DI;
use Selibra\Event\Exception\StoppableEventException;

class Listener
{

    const LISTENER_TYPE_CLASS = 'class';
    const LISTENER_TYPE_METHOD = 'method';

    /**
     * @var string
     */
    private string $type = 'class';


    /**
     * @var string
     */
    private string $class;

    /**
     * @var string
     */
    private string $method;

    public function __construct()
    {
    }

    /**
     * @param object $event
     * @throws \Selibra\Di\Exception\NoImplementClass
     * @throws StoppableEventException
     */
    public function execute(object $event)
    {
        $listenerObject = DI::getObjectContext($this->getClass());
        if( $this->type === self::LISTENER_TYPE_CLASS ){
            // 执行对象
            $listenerObject->listen($event);
            if( $listenerObject instanceof StoppableEventInterface){
                if( $listenerObject->isPropagationStopped() ){
                    throw new StoppableEventException($this->getClass().' Listener Stopped.');
                }
            }
        }else{
            // 触发方法
            $method = $this->getMethod();
            $listenerObject->$method($event);
        }
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return $this->type;
    }

    /**
     * @param string $type
     */
    public function setType(string $type): void
    {
        $this->type = $type;
    }

    /**
     * @return string
     */
    public function getClass(): string
    {
        return $this->class;
    }

    /**
     * @param string $class
     */
    public function setClass(string $class): void
    {
        $this->class = $class;
    }

    /**
     * @return string
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    /**
     * @param string $method
     */
    public function setMethod(string $method): void
    {
        $this->method = $method;
    }

}